#include "utils.h"

namespace utils
{
vector<string> explode(const string &inString,const string &separator)
{
    vector<string> returnVector;
    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = inString.find (separator, start)) != string::npos)
    {
        returnVector.push_back (inString.substr (start, end-start));
        start = end + separator.size();
    }
    returnVector.push_back (inString.substr (start));
    return returnVector;
}

/*template <class T> string toString(const T& a)
{
    ostringstream ost;
    ost << a;
    return ost.str();
}

template<typename T>T fromString( const std::string& s)
{
    std::istringstream is(s);
    T t;
    is >> t;
    return t;
}
string md5(const string& str)
{
    hashwrapper *myWrapper = new md5wrapper();
    string hash1 = myWrapper->getHashFromString(str);
    delete myWrapper;
    return hash1;
}
*/
string zotero_path_decode(const string& str)
{
    //only convert chinese now
    string r;
    for(int i=0; i<str.size(); i++)
    {
        if (str[i]==-61 && i<str.size()-5 && str[i+1]<-79 && str[i+2]==-62 && str[i+4]==-62)
        {
            r+=str[i+1]+64;
            r+=str[i+3];
            r+=str[i+5];
            i+=5;
        }
        else
        {
            r+=str[i];
        }
    }
    return r;
}
//TODO:实现特殊字符串的替换，保证SQL字符串的安全
//替换一个单引号为两个单引号
string escapeSQL(const string& str)
{
    string tmp=str;
    if (str == "NULL")	return "NULL";
    for(int i=0; i<tmp.size(); i++)
    {
        if (tmp[i]==39)
        {
            tmp.replace(i,1,"''");
            i++;
        }
    }
    return tmp;
}
string replace(const string& str, const char f, const char t)
{
    string des;
    for(int i=0; i<str.size(); i++)
    {
        if (str[i]==f)
            des+=t;
        else
            des+=str[i];
    }
    return des;
}
string random_zotero_key(int len,string base)
{
    if (base.empty()) base="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    string randomstring;
    //srand ( time(NULL) );
    for (int i=0; i<len; i++)
    {
        randomstring += base[rand()% base.size()];
    }
    return randomstring;
}
string random_zotero_key(int len)
{
    return random_zotero_key(len,"");
}
string get_data_dir()
{
#ifndef PACKAGE_DATA_DIR
    return "./";
#else
    return PACKAGE_DATA_DIR;
#endif
}
};
